<?php
/**
 * A QueryBehaviour implementation for faceting. 
 * This class provides the methods required to add faceting
 * to a query such as adding facet fields and filtering
 * on them.
 *
 * @author Rob Young <rob@roryoung.co.uk>
 * @package forage.behaviours.faceting
 */
class ForageFacetingQueryBehaviour extends ForageQueryBehaviour
{
  /**
   * Facets which have been added to this query
   *
   * @var array
   */
  private $fields  = array();

  /**
   * Facets which are being filtered on and the values with which they are being filtered
   *
   * @var array
   */
  private $filters = array();

  public function __get($name)
  {
    switch ($name) {
    case 'facet_fields':
      return $this->fields;
    }
  }

  /**
   * Set the fields which should be facetable
   *
   * @param array $fields
   */
  public function setFacetFields($fields)
  {
    $this->fields = $fields;
  }
  
  /**
   * Add a value to filter a given facet by
   *
   * @param string $field
   * @param string $value
   */
  public function addFacetFilter($field, $value)
  {
    if (!in_array($field, $this->fields)) {
      throw new ForageException("Cannot filter on a field which has not been set.");
    }
    if (!isset($this->filters[$field])) {
      $this->filters[$field] = array();
    }
    $this->filters[$field][] = $value;
  }

  /**
   * Get the filters which are currently applied
   * to the query. Optionally just get the filters
   * applied to a particular field.
   *
   * @param string $field
   * @return array
   */
  public function getFacetFilters($field=null)
  {
    if ($field) {
      return @$this->filters[$field];
    } else {
      return $this->filters;
    }
  }
}
